<?php
namespace Cyfy\Modules\Articles;
use \Cyfy\Modules\Locale\Locale;
use \Cyfy\Modules\DibiPager\DibiPager;
use \Cyfy\Modules\BasicContent\Content;
use \Cyfy\Modules\Objects\Collapsible;
use \Cyfy\Modules\Users\Current;

class Module extends \Cyfy\Module
{
    const IMAGE_DIR = "articles/";
    const IMAGE_ORIGINAL_DIR = "articles/orig/";
    const PER_PAGE = 5;
    const IN_BLOCK = 2;
    const CROP_TEXT_TO = 600;
    const ARTICLE_PATH_PREFIX = "Y-m-d-"; 
    
    static $settings = array("perPage", "inBlock", "imageWidth", "imageHeight");


    static function blocks($sid = 0)
    {
        if($sid){
            return self :: getShort($sid);
        }
        return self :: getSections();
    }
    
    
    static function administration($name = "")
	{
		// something selected?
        switch($name)
        {
            case "newArticle":
                $form = new Forms\NewArticle();
                return $form -> show(); 
                
            case "settings":
                return self :: settings();
                
            case "editArticle":
                $aid = \Cyfy\Cyfy :: arg(3);
                $result = \dibi :: query("SELECT * FROM [:cyfy:Articles-articles] WHERE [aid] = %i ", $aid);
                if(count($result) == 0) return false;
                $article = $result -> fetch();
                
                $c = Content :: load($article["bcid"]);
                if(!$c) return false;
                $article["text"] = $c -> getContent();
        
                $form = new Forms\EditArticle();
                $form -> setData($article);
                return $form -> show(); 
                
            case "":
                return array(
                    "newArticle" => array("name" => self :: t(10), "description" => self :: t(20), "permission"=> "write and edit"),
                    "editArticle" => array("name" => self :: t(50), "description" => self :: t(60), "permission"=> "write and edit", "hidden" => true),
                    "settings" => array("name" => self :: t(30), "description" => self :: t(40), "permission" => "administration")
                );
		}	
	}
    
    
    static function ajax($name)
    {
        switch($name)
        {
            case "articles":
                return self :: ajaxArticles($_POST["sid"]);
                
            case "deleteArticle":
                return self :: ajaxDeleteArticle($_POST["aid"]);
            
            case "deleteSection":
                return self :: ajaxDeleteSection($_POST["sid"]);
                
            case "sectionsAdmin":
                return self :: ajaxSectionsAdmin();
        }
    
    }
    
    
    static function get($id)
    {
        if($id == "article")
        {
            return self :: detail(\Cyfy\Cyfy :: arg(1));
        }
        
        if($id == "all")
        {
            return self :: viewAll();
        }

        return self :: listOf($id);
    }
    
    
    
    static public function getSections($key = "sid")
    {
        $result = \dibi :: query("SELECT [{$key}], [title] FROM [:cyfy:Articles-sections] ORDER BY [title] ASC");
        if(count($result) == 0) return array();
        
        return $result -> fetchPairs($key, 'title');
    }
    
    
    static private function viewAll()
    {
        \Cyfy\Template :: setTitle(self :: t(70));
        
        $sections = self :: getSections("path");
        if(count($sections) > 1)
        {
            $output = "<h2>" . self :: t(1200) . "</h2>";
            foreach($sections as $path => $title)
            {
                $output .= "<h3><a href=\"{$path}\">" . $title . "</a></h3>";
            }
            $output .= "<h2>" . self :: t(1100) . "</h2>";
        }
        else
        {
            $output .= "<h2>" . self :: t(70) . "</h2>";
        }
        
        $pager = new DibiPager("articles", self :: Constant("perPage"));		
        $pager -> ajaxCall("Articles","articles", '#articles');
        
        $output .= "<div id=\"articles\">" . self :: ajaxArticles() . "</div>";
        $output .= $pager -> pager("SELECT count(*) FROM [:cyfy:Articles-articles]");			

        return $output;
    }
    
    
    
    
    
    static private function listOf($sid)
    {
        // get section
        $result = \dibi :: query("SELECT * FROM [:cyfy:Articles-sections] WHERE [sid] = %s ", $sid);
        if(count($result) == 0) return false;
        $section = $result -> fetch();
        
        
		\Cyfy\Template :: setTitle( $section["title"]);
        
        $output .= "<h2>" .  $section["title"] . "</h2>\n";
        $pager = new DibiPager("articles", self :: Constant("perPage"));		
        $pager -> ajaxCall("Articles","articles", '#articles', 'sid=' . $sid);
        
        $output .= "<div id=\"articles\">" . self :: ajaxArticles($sid) . "</div>";
        $output .= $pager -> pager("SELECT count(*) FROM [:cyfy:Articles-articles] WHERE [sid] = {$sid}");			
        return $output;
    }
    
    static private function getShort($sid)
    {
        // get section
        $result = \dibi :: query("SELECT * FROM [:cyfy:Articles-sections] WHERE [sid] = %s ", $sid);
        if(count($result) == 0) return false;
        
        $section = $result -> fetch();

        $url =  \Cyfy\Cyfy :: getPath($section["path"]);
        $output = "<h3><span><a href=\"" . $url . "\">" . $section["title"] . "</a></span></h3>\n";
    
        $limit = (self :: constant("inBlock")) ? self :: constant("inBlock") : self :: IN_BLOCK;

        // select Articles
        $result = \dibi :: query("SELECT [image], [title], [short], [aid], [path] FROM [:cyfy:Articles-articles] WHERE [sid] = %s ", $sid ," ORDER BY [time] DESC LIMIT %i", $limit);
	
        // Articles itetator
		foreach($result as $a)
		{
            $link = \Cyfy\Cyfy :: getPath("articles/" . $a["path"]);
            
            // building a Article... templates someday??
$output .= <<<OUTPUT
<div class="article"> 
    <h4 class="title"><a href="{$link}">{$a["title"]}</a></h4>
    <p class="description">{$a["short"]}</p>
</div>             
OUTPUT;
        }
        $output .= "<p class=\"read-all\"><a href=\"{$url}\">" . self :: t(1000) . "</a></p>";
        return $output;
    }






    
    static private function ajaxArticles($sid = "")
    {
        // pager declaration and ajax
        $pager = new DibiPager("articles", self :: Constant("perPage"));		
        
        if($sid != ""){
            $sid = "WHERE [sid] = $sid";
        }
        
        $result = $pager -> query("SELECT * FROM [:cyfy:Articles-articles] $sid ORDER BY [time] DESC");
	
		// if no results, exit with no Articles found
		if(count($result) == 0){
			return \Cyfy\Message :: get( self :: t(90), \Cyfy\Message::WARNING);
		}
		

        
        // Articles itetator
		foreach($result as $a)
		{
            $link = \Cyfy\Cyfy :: getPath("articles/" . $a["path"]);
            if($a["image"]){
                $i = \Cyfy\Cyfy :: getSourcePath(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_DIR . $a["image"]);
                $image = "<div class=\"image\"><img src=\"" . $i . "\" alt=\"{$a["title"]}\"></div>";
            }else{
                $image = "";
            }
            $time = Locale :: getTime($a["time"], true);
            // building a Article... templates someday??
$output .= <<<OUTPUT
<div class="article"> 
    <p class="time">$time</p>
    <h3 class="title"><a href="{$link}">{$a["title"]}</a></h3>
    <a href="{$link}">$image</a>
    <p class="description">{$a["short"]}</p>
</div>             
OUTPUT;
        }
        return $output;
    }
    
    
    
    
    
    
    
    
    
    static private function detail($path)
    {
         
         
        $result = \dibi :: query("SELECT * FROM [:cyfy:Articles-articles] WHERE [path] = %s", $path);	
        
        // if not found
        if(count($result) == 0)
        {
            $_SESSION["404url"] = "articles/" . $path;
            \Cyfy\Cyfy :: redirectTo('error/404');
            return false;
        }
        $a = $result -> fetch();
		
        $c = Content :: load($a["bcid"]);
        if(!$c) return false;
        
        // get
        \Cyfy\Template :: setTitle($c -> getTitle());
        $output .= "<h2>" . $c -> getTitle() . "</h2>\n";
        if($a["image"])
        {
            $i = \Cyfy\Cyfy ::  getSourcePath(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_DIR . $a["image"]);
            $output  .= "<div class=\"article-image\"><img src=\"" . $i . "\" alt=\"{$a["title"]}\"></div>";
        }
        $output .= "<p class=\"article-time\">" . Locale :: getTime($a["time"], true) . "</p>\n";
        
        $output .= $c -> get("", false);
        
        // more edit options:
        if(\Cyfy\Cyfy ::  permission("Articles", "write and edit") && ($c -> isEditable() || $c -> isDeletable()))
        {
            $output .= "<ul class=\"bcMoreEditOptions\">";
            if($c -> isEditable()){
                $output .= "<li> <a class=\"button\" href=\"" . \Cyfy\Cyfy ::  getPath("administration/Articles/editArticle/{$a["aid"]}") . "\">" . self :: t(100) . " </a></li>";
            }
            if($c -> isDeletable()){
                $output .= "<li> <a class=\"button\" href=\"#\" onclick=\"if(confirm('" . self :: t(121, array($a["title"])) . "')){ Cyfy.ajax('Articles', 'deleteArticle', '', 'aid={$a["aid"]}', 'Cyfy.redirectTo(\'articles\');');} return false;\">" .  self :: t(110) . " </a></li>";
            }
            $output .= "</ul>";
        }
        
        // comments
        if(\Cyfy\Modules :: isEnabled("Comments"))
        {
            $output .= \Cyfy\Modules\Comments\Module :: getComments("Articles", $a["aid"]);
        }
        
        return $output;
    
    }
    
    
    
    static private function ajaxDeleteArticle($aid)
    {
        if(!\Cyfy\Cyfy ::  permission("Articles", "write and edit"))
        {
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
                
        $result = \dibi :: query("SELECT [aid], [bcid], [image] FROM [:cyfy:Articles-articles] WHERE aid = %i", $aid);
        // if no results, exit with no Articles found
		if(count($result) == 0){
			\Cyfy\Message :: set( self :: t(210), \Cyfy\Message::ERROR);
            return false;
		}
		
        $e = $result -> fetch();
        
        
        if(Content :: deleteStatic($e["bcid"]))
        {
            // delete thumbnails
            if($e["image"]){
                \Cyfy\Cyfy ::  delete(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_DIR . $e["image"]);
                \Cyfy\Cyfy ::  delete(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_ORIGINAL_DIR . $e["image"]);
            }
            // delete from db
            \dibi :: query("DELETE FROM [:cyfy:Articles-articles] WHERE aid = %i", $aid);
            
			\Cyfy\Message :: set( self :: t(320));
            return true;
        }
        \Cyfy\Cyfy ::  noPermission();
        return false;
    }
    
    
    static private function settings()
    {
        
       
        
        // settings
        $form = new Forms\Settings();
        $form -> setDataFromConstants(self :: $settings);
        $output .= $form -> show(); 
    
    
        // sections
        $output .= "<h2>" . self :: t(500) . "</h2>";
        $pager = new DibiPager("sectionsList");
        $pager -> ajaxCall("Articles", "sectionsAdmin", "#sections-admin");
        $output .= "<div id=\"sections-admin\">" . self :: ajaxSectionsAdmin() . "</div>";
        $output .= $pager -> pager("SELECT count(*) FROM [:cyfy:Articles-sections]"); ///////// TODO TODO
        
        $output .= "<h3>" . self :: t(510) . "</h3>";
        $form = new Forms\NewSection();
        $output .= $form -> show();
        
        $output .= "";
        return $output;
    }
    
    static private function ajaxSectionsAdmin()
    {
        if(!Current :: hasPermission("Articles", "administration"))
        {
            return false;
        }
        
        
    
        $table = new \Cyfy\Modules\Objects\Table();
        
    
        $pager = new DibiPager("sectionsList");
        $result = $pager -> query("SELECT * FROM [:cyfy:Articles-sections]");
        
        if(count($result) == 0){
            return \Cyfy\Message :: get(self :: t(550), \Cyfy\Message::WARNING);
        }
        
        $table -> header(array(self :: t(520), self :: t(530), self :: t(540)));
        foreach($result as $s)
        {
            $btn = "<input type=\"submit\" onclick=\"Cyfy.ajax('Articles', 'deleteSection', '', 'sid={$s["sid"]}', 'Cyfy.ajax(\'Articles\', \'sectionsAdmin\', \'#sections-admin\');')\" value=\"D\" />";
            $table -> row(array($s["title"], $s["path"], $btn));
        }
        
        return $table -> show();
    }
    
    static private function ajaxDeleteSection($sid)
    {
        if(!Current :: hasPermission("Articles", "administration"))
        {
            return false;
        }
       
        $result = \dibi :: query("SELECT * FROM [:cyfy:Articles-sections] WHERE [sid] = %s", $sid);
        if(count($result) == 0){
            return false;
        }
        
        $s = $result -> fetch();
        
        \Cyfy\Cyfy :: unregisterPath($s["path"]);
        
        \dibi :: query("DELETE FROM [:cyfy:Articles-sections] WHERE [sid] = %s", $sid);
        \Cyfy\Message :: set(self :: t(841, array($s["title"])));
        return true;
    }
    
    
    static function rebuildThumbnails()
    {
        $w = self :: constant("imageWidth");
        $h = self :: constant("imageHeight");
        // checking
        if(!$w || !$h)
        {
            return false;
        }
            
        // load dir
        $files = scandir(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_ORIGINAL_DIR);
        array_shift($files);
        array_shift($files);
        
        // resize them
        foreach($files as $filename)
        {
            $i = new \Cyfy\Modules\Image\Image(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_ORIGINAL_DIR . $filename);
            $i -> resize($w, $h);
            $i -> saveAs(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_DIR . $filename);
            $i -> close();
        }
        
        return true;
    }
}
